package com.example.lottery_system.contoller;

import com.example.lottery_system.common.pojo.CommonResult;
import com.example.lottery_system.common.utils.JacksonUtil;
import com.example.lottery_system.contoller.param.DrawPrizeParam;
import com.example.lottery_system.contoller.param.ShowWinningRecordsParam;
import com.example.lottery_system.contoller.result.WinningRecordsResult;
import com.example.lottery_system.service.DrawPrizeService;
import com.example.lottery_system.service.dto.WinningRecordsDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DrawPrizeController {

    private final static Logger logger = LoggerFactory.getLogger(DrawPrizeController.class);

    @Autowired
    private DrawPrizeService drawPrizeService;


    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@Validated @RequestBody DrawPrizeParam param) {
        logger.info("drawPrize DrawPrizeParam:{}", param);

        // service
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordsResult>> showWinningRecords(@Validated @RequestBody ShowWinningRecordsParam param) {
        logger.info("showWinningRecords ShowWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));

        List<WinningRecordsDTO> winningRecordsDTOList = drawPrizeService.getRecords(param);
        return CommonResult.success(convertToWinningRecordsResult(winningRecordsDTOList));
    }

    private List<WinningRecordsResult> convertToWinningRecordsResult(List<WinningRecordsDTO> winningRecordsDTOList) {
        if(CollectionUtils.isEmpty(winningRecordsDTOList)) {
            return Arrays.asList();
        }

        return winningRecordsDTOList
                .stream()
                .map(winningRecordsDTO -> {
                    WinningRecordsResult result = new WinningRecordsResult();
                    result.setPrizeName(winningRecordsDTO.getPrizeName());
                    result.setPrizeTier(winningRecordsDTO.getPrizeTier().getMessage());
                    result.setWinnerId(winningRecordsDTO.getWinnerId());
                    result.setWinnerName(winningRecordsDTO.getWinnerName());
                    result.setWinningTime(winningRecordsDTO.getWinningTime());
                    return result;
                }).collect(Collectors.toList());
    }
}
